package com.fw.service.globalsetting.impl;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;

import com.fw.service.globalsetting.GlobalSettingService;
import com.fw.service.globalsetting.bean.GlobalSettingBean;
import com.fw.util.SpringPropertyUpdater;

public class GlobalSettingServiceImpl implements GlobalSettingService {

    @Autowired
    private Properties globalSettingProperties;

    @Autowired
    private SpringPropertyUpdater springPropertyUpdater;

    @Override
    public GlobalSettingBean getGlobalSetting() {
	GlobalSettingBean globalSettingBean = new GlobalSettingBean();
	globalSettingBean.setPayAtAllServiceInquiryPeriod(this.getPropertyValue("payAtAllServiceInquiryPeriod"));
	globalSettingBean.setTransactionReportMaximumPeriodSearchAeonUser(this
		.getPropertyValue("transactionReportMaximumPeriodSearchAeonUser"));
	globalSettingBean.setTransactionReportMaximumPeriodSearchMerchantUser(this
		.getPropertyValue("transactionReportMaximumPeriodSearchMerchantUser"));
	globalSettingBean.setAuditLogMaximumPeriodSearch(this.getPropertyValue("auditLogMaximumPeriodSearch"));
	return globalSettingBean;
    }

    @Override
    public GlobalSettingBean setGlobalSetting(GlobalSettingBean globalSettingBean) {
	if (globalSettingBean != null) {
	    this.setPropertyValue("payAtAllServiceInquiryPeriod", globalSettingBean.getPayAtAllServiceInquiryPeriod());
	    this.setPropertyValue("transactionReportMaximumPeriodSearchAeonUser",
		    globalSettingBean.getTransactionReportMaximumPeriodSearchAeonUser());
	    this.setPropertyValue("transactionReportMaximumPeriodSearchMerchantUser",
		    globalSettingBean.getTransactionReportMaximumPeriodSearchMerchantUser());
	    this.setPropertyValue("auditLogMaximumPeriodSearch", globalSettingBean.getAuditLogMaximumPeriodSearch());

	    // update properties
	    try {
		springPropertyUpdater.updateProperties("globalSettingProperties", globalSettingProperties, "");
	    } catch (Exception e) {
		e.printStackTrace();
	    }

	}
	return globalSettingBean;
    }

    private Integer getPropertyValue(String fieldName) {
	Integer integerValue = null;
	String stringValue = globalSettingProperties.getProperty(GlobalSettingBean.class.getName() + "." + fieldName, null);
	if (stringValue != null) {
	    integerValue = Integer.valueOf(stringValue);
	}
	return integerValue;
    }

    private void setPropertyValue(String fieldName, Integer integerValue) {
	if (integerValue != null) {
	    globalSettingProperties.setProperty(GlobalSettingBean.class.getName() + "." + fieldName, String.valueOf(integerValue));
	}
    }

}
